package com.dg.river.netty.auditdev;


import com.dg.river.netty.axle.msg2dev.DevMsg;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;

public class AuditDevClientHandler extends ChannelInboundHandlerAdapter {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    private AuditDevClient client;

    public AuditDevClientHandler(AuditDevClient client) {
        this.client = client;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.debug(ctx.channel().remoteAddress().toString());
        DevMsg in = (DevMsg) msg;
        //根据报文类型，处理业务
        /*
        switch (in.getHeader().getMsgType()) {
            case MessageConst.MTYPE_HEARTPONG: //心跳
                handleMsg23(in);
                break;
            case MessageConst.MTYPE_RESULT:
                handleMsg99(in);
                break;
            case MessageConst.MTYPE_WX_MICROPAY_RESP: //微信刷卡回复
                handleWxMicropayResp(in);
                break;
        }
        */
        logger.debug(in.toString());
        //转到客户端处理
        client.onRecvMsg(in);

        ReferenceCountUtil.release(msg);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (IdleStateEvent.class.isAssignableFrom(evt.getClass())) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE)
                logger.debug("read idle");
            else if (event.state() == IdleState.WRITER_IDLE) {
                logger.debug("write idle, send ping message");
                client.sendPingMsg();
            } else if (event.state() == IdleState.ALL_IDLE)
                logger.debug("all idle");
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        //当客户端断开连接时，重新连接
        client.onDisconnect();
    }


}
